package com.xx.xiawan.net;
import java.util.concurrent.ExecutionException;

import android.content.Context;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.RequestFuture;
import com.android.volley.toolbox.Volley;

/**
 * Created by Administrator on 2017-08-23.
 */


public class DGHttpClient {
    private static volatile DGHttpClient sClient;
    private static final Object sSyncLock = new Object();
    private final RequestQueue mRequestQueue;

    private DGHttpClient(Context context) {
        mRequestQueue = Volley.newRequestQueue(context);
    }

    public static DGHttpClient newClient(Context context) {
        return new DGHttpClient(context);
    }

    public static DGHttpClient defaultClient(Context context) {
        if (sClient == null) {
            synchronized (sSyncLock) {
                if (sClient == null) {
                    sClient = new DGHttpClient(context);
                }
            }
        }
        return sClient;
    }

    public <Result> Result doRequest(PostSyncRequest<Result> request)
            throws RequestException {
        RequestFuture<Result> future = request.getFuture();
        mRequestQueue.add(request);
        try {
            return future.get();
        } catch (InterruptedException | ExecutionException e) {
            throw new RequestException(e);
        }
    }

    public void doRequest(Request<?> request){
        mRequestQueue.add(request);
    }

    public static void exit(Context context){
        DGHttpClient.defaultClient(context).quit();
        sClient = null;
    }

    public void quit(){
        mRequestQueue.stop();
    }
}
